package com.dongdongshop.shiro.config;


import com.alibaba.dubbo.config.annotation.Reference;
import com.dongdongshop.pojo.TbSeller;
import com.dongdongshop.service.SellerService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;



import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

public class UserRealm extends AuthorizingRealm {
    @Reference
    private SellerService sellerService;

    //执行授权逻辑
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行授权逻辑");
        //给资源进行授权
        SimpleAuthorizationInfo authorizationInfo= new SimpleAuthorizationInfo();
        //查询数据库，获取用户拥有的权限
        List<String> perms = new ArrayList<>();
        perms.add("delete");
        //将数据库查询迟来的权限添加到authorizationInfo中
        authorizationInfo.addStringPermissions(perms);
        return authorizationInfo;
    }
    //执行认证逻辑
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行认证逻辑");
        //编写shiro判断逻辑，判断用户名和密码
        UsernamePasswordToken token = (UsernamePasswordToken)authenticationToken;
        TbSeller seller = sellerService.getInfoToLogin(token.getUsername());

        if(seller == null || !"1".equals(seller.getStatus())){
            //用户名不存在
            //我们只需要return个null值，shiro底层会抛出UnknownAccountException异常
            return null;
        }
        //判断密码
        //第一个参数：数据库查询出来的对象，登录成功后shiro会把这个对象放到session中
        //第二个参数：数据库查询出来的密码，shiro会自动效验
        //第三个参数：登录成功后用户的真实姓名
        //return new SimpleAuthenticationInfo("",token.getPassword(),"");
        //如果设置了加密方式
        return new SimpleAuthenticationInfo(seller,seller.getPassword(),ByteSource.Util.bytes(seller.getSalt()),seller.getName());
    }
}
